package org.tinygroup.earthworm;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.earthworm.util.EarthWormHelper;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class EarthWormJsonSupport implements LogSupport {
	private final static String STATUS_SUCCESS = "0";
	private final static String STATUS_FAIL = "1";
	private final static String R0 = "r0";
	private final static String A0 = "a0";
	private final static String BDQX_PRE = "0.";
	private final static String RESULT_OF_SKIP = "";
	private final static String HEART_BEAT = "heart_beat_key_node_client";
	private final static String KEY_INFO ="info";
	private final static String KEY_ERRORMSG = "errorMsg";
	private final static String KEY_MYPACKAGE ="myPackage";
	private final static Logger LOGGER = LoggerFactory.getLogger(EarthWormJsonSupport.class);
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	
	
	
	public String getLogMessage(String stage) {

		RpcContext rpcContext = RpcContext.get();
		//过滤心跳
		if(HEART_BEAT.equals(rpcContext.tag)){
			return RESULT_OF_SKIP;
		}
		//过滤其他阶段
		String depotID = "";
		if(EarthWormHelper.STAGE_SS.equals(stage)||EarthWormHelper.STAGE_CR.equals(stage)){
			depotID = A0;
		}else if(EarthWormHelper.STAGE_CS.equals(stage)||EarthWormHelper.STAGE_SR.equals(stage)){
			depotID = R0;
		}
		if(StringUtil.isBlank(depotID)){
			return RESULT_OF_SKIP;
		}
		JSONObject json = new JSONObject();
		//0成功 1失败
		String responseStatus = STATUS_FAIL;
		//版本固定
		String version = STATUS_SUCCESS;
		//固定
		String spanType = STATUS_SUCCESS;
		//服务id
		String spanName = rpcContext.tag;
		if (StringUtil.isBlank(rpcContext.errorMsg)) {
			responseStatus = STATUS_SUCCESS;
		}else{
			rpcContext.customInofos.put(KEY_ERRORMSG, rpcContext.errorMsg);
		}
		//适配bdqx的
		
		String spanId = BDQX_PRE+rpcContext.spanId;
		
		String[] info = new String[] { rpcContext.traceId, spanId, depotID, stage, dateFormat.format(new Date()),
				rpcContext.tag, rpcContext.target, responseStatus, version, spanType, spanName };
		json.put(KEY_INFO, info);
		JSONObject myPackage = new JSONObject();
		Map<String, String> customInofos = rpcContext.customInofos;
		
		if(MapUtils.isEmpty(customInofos)){
			String jsonString = json.toJSONString();
			LOGGER.debugMessage("{}",jsonString);
			return jsonString;
		}
		for (String key : customInofos.keySet()) {
			myPackage.put(key, customInofos.get(key));
		}
		json.put(KEY_MYPACKAGE, myPackage.toJSONString());
		String jsonString = json.toJSONString();
		LOGGER.debugMessage("{}",jsonString);
		return jsonString;
	}

}
